<template>
  <main v-if="statusCode === 200">
    <Row>
      <left-module 
        :blogList="blogList"
        :totalBlog="totalBlog"
        :currentPage="currentPage"
        :pageSize="pageSize"
        @changePage="changePage"
      ></left-module>
      <right-module></right-module>
    </Row>
  </main>
  <not-found v-else></not-found>
</template>

<script>
import { findBlogByTypeId } from 'service'

export default {
  name: 'Category',
  data() {
    return {
      totalBlog: 0,
      currentPage: +this.$route.query.page || 1,
      pageSize: 12,
      typeName: '',
      blogList: [],
      flag: true,
      statusCode: 200
    }
  },
  created() {
    this.getCategory()
  },
  computed: {
    typeList() {
      return this.$store.getters['blog/types']
    }
  },
  methods: {
    async getCategory() {
      var id = this.$route.params['id']
      // 获取分类名 
      this.typeList.forEach(item => {
        if (item.childTypes != null) {
          item.childTypes.forEach(child => {
            if (id == child.id) {
              this.typeName = child.name
            }
          })
        } else if (id == item.id) {
          this.typeName = item.name
        }
      })
      let res = await findBlogByTypeId(this.currentPage, this.pageSize, id)
      this.statusCode = res.data.statusCode 
      if (this.statusCode === 200) {
        this.blogList = res.data.data.list
        this.totalBlog = res.data.data.total
        document.title = `${this.typeName} - ${this.documentTitle}`
      }
    },
    async changePage(currentPage) {
      this.currentPage = currentPage
      await this.getCategory()
      this.flag = false
      let query = currentPage === 1 ? {} : { page: currentPage }
      this.$router.push({ name: 'category', query: query })
    }
  },
  watch: {
    $route(to, from) {
      if (this.flag && to.name === 'category') {
        this.currentPage = +to.query.page || 1
        this.getCategory()
      }
      this.flag = true
    }
  },
  components: {
    "left-module": () => import("components/homePage/LeftModule"),
    "right-module": () => import("components/homePage/RightModule"),
  }
}
</script>

<style lang='scss' scoped>
</style>